package com.liao.common.advice;

import com.alibaba.fastjson.JSON;
import com.liao.common.annotation.ExcludeFromResponseAdvice;
import com.liao.common.utils.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@ControllerAdvice
@ResponseBody
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查类或方法上是否有排除注解
        boolean hasClassAnnotation = returnType.getContainingClass().isAnnotationPresent(ExcludeFromResponseAdvice.class);
        boolean hasMethodAnnotation = returnType.hasMethodAnnotation(ExcludeFromResponseAdvice.class);

        // 如果存在排除注解，则返回 false（不处理）
        return !(hasClassAnnotation || hasMethodAnnotation);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {

        if (body instanceof String) {
            return JSON.toJSONString(Result.success(body));
        }
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}